package com.zhang.spring.boot.mongo;

import com.mongodb.client.MongoClient;
import com.zhang.data.mongo.core.MongoUtil;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class MongoRespFactoryBean implements FactoryBean, InitializingBean {

    private Object object;
    private Class type;

    private MongoClient mongoClient;

    private MongoUtil mongoUtil;

    public void setObject(Object object) {
        this.object = object;
    }

    public Class getType() {
        return type;
    }

    public void setType(Class type) {
        this.type = type;
    }

    public MongoClient getMongoClient() {
        return mongoClient;
    }

    public void setMongoClient(MongoClient mongoClient) {
        this.mongoClient = mongoClient;
        this.mongoUtil = new MongoUtil(mongoClient,"test");
    }

    @Override
    public Object getObject() throws Exception {
        return object;
    }

    @Override
    public Class<?> getObjectType() {
        return type;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        ProxyFactory result = new ProxyFactory();
        result.setTarget(type);
        ParameterizedType parameterizedType=(ParameterizedType) type.getGenericInterfaces()[0];
        Type geType=parameterizedType.getActualTypeArguments()[0];
        Class<?> clazz = (Class<?>)geType;
        result.setInterfaces(new Class[]{ type,MongoRepository.class});
        result.addAdvice(new QueryExecutorMethodInterceptor(new SimpleMongoRepository(this.mongoUtil,clazz),this.mongoUtil,clazz));
        object =result.getProxy();

    }
}
